import { addRole, authRole, deleteRole, editRole, getRoleList } from '@/services/roles';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { useRef } from 'react';
import { Button, message, Modal } from 'antd';
import AddOrEditRoleModal from './AddOrEditRoleModal';
import AuthRoleModal from './AuthRoleModal';

const RolesManage: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const delRole = (id: string) => {
    Modal.confirm({
      title: '温馨提示',
      content: '确定删除该用户吗？',
      okType: 'danger',
      async onOk() {
        return deleteRole({ id }).then((res) => {
          if (res.success) {
            message.success('删除成功');
            actionRef.current?.reload();
          }
        });
      },
    });
  };

  const onAddRole = async (values: Record<string, any>) => {
    const hideMessageLoading = message.loading('处理中...', 0);
    return addRole(values as ROLE.AddRoleParams)
      .then((res) => {
        if (res.success) {
          message.success('添加成功');
          actionRef.current?.reload();
          return true;
        }
        return false;
      })
      .catch(() => {
        return false;
      })
      .finally(() => {
        hideMessageLoading();
      });
  };

  const onEditRole = async (value: ROLE.EditRoleParams) => {
    const hideMessageLoading = message.loading('处理中...', 0);
    return editRole(value)
      .then((res) => {
        if (res.success) {
          message.success('修改成功');
          actionRef.current?.reload();
          return true;
        }
        return false;
      })
      .catch(() => {
        return false;
      })
      .finally(() => {
        hideMessageLoading();
      });
  };

  const onAuthRole = async (menuIds: string[], roleId: string) => {
    return authRole({
      id: roleId,
      menuIdArr: menuIds,
    })
      .then((res) => {
        if (res.success) {
          message.success('授权成功');
          actionRef.current?.reload();
          return true;
        }
        return false;
      })
      .catch(() => {
        return false;
      });
  };

  const columns: ProColumns<ROLE.RoleType>[] = [
    {
      title: '序号',
      width: 80,
      valueType: 'index',
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      search: {
        transform: (val) => ({ roleName: val }),
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      //  render: (_, record) => <Input.Password defaultValue={record.userPassword} />
    },
    {
      title: '授权时间',
      hideInSearch: true,
      dataIndex: 'authTime',
    },
    {
      title: '授权人',
      dataIndex: 'authName',
      hideInSearch: true,
    },
    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      // 系统默认用户不可操作
      render: (_, record) =>
        record.id === 'JS001'
          ? [
              <AuthRoleModal
                key="role_auth_detail_modal"
                actionType="detail"
                roleId={record.id}
                triggerEl={<a key="role_auth">查看授权</a>}
              />,
            ]
          : [
              <AuthRoleModal
                key="role_auth_detail_modal"
                actionType="detail"
                roleId={record.id}
                triggerEl={<a key="role_auth">查看授权</a>}
              />,
              <AddOrEditRoleModal
                key="edit_role_modal"
                actionType="edit"
                editRoleInfo={record}
                triggerEl={<a>编辑</a>}
                onFinished={async (values) => {
                  return onEditRole({
                    roleName: values.roleName,
                    id: record.id,
                  });
                }}
              />,
              <AuthRoleModal
                key="role_auth_modal"
                actionType="auth"
                roleId={record.id}
                triggerEl={<a key="role_auth">角色授权</a>}
                onFinished={async (ids) => onAuthRole(ids, record.id)}
              />,
              <a
                key="role_delete"
                onClick={() => {
                  delRole(record.id);
                }}
              >
                删除
              </a>,
            ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<ROLE.RoleType, ROLE.RoleParams>
        actionRef={actionRef}
        columns={columns}
        request={async (params) => {
          const res = await getRoleList(params);
          return {
            data: res.data?.list || [],
            success: res.success,
            total: res.data?.total || 0,
          };
        }}
        rowKey="id"
        pagination={{
          showQuickJumper: true,
        }}
        toolBarRender={() => [
          <AddOrEditRoleModal
            key="add_role_modal"
            actionType="add"
            onFinished={onAddRole}
            triggerEl={<Button type="primary">新增</Button>}
          />,
        ]}
      />
    </PageContainer>
  );
};

export default RolesManage;
